package com.zpz.framework.zpzoauth.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
 * @author zhangpanzhi
 * @time 2019-07-09
 * @description 未经本人允许请勿随便改动，尊重劳动
 * */
@Configuration
public class ZpzOauthDecodeJwt {
    private static Logger logger = LoggerFactory.getLogger(ZpzOauthDecodeJwt.class);
    /*
    * springboot 不允许将值注入给静态变量，可以借用spring的set方法给静态变量赋值
    * */
    /*
    * 获取用户当前登录用户所有的用户信息
    * */
    public static Map<String,String> getUserInfo(String auth){
        Map<String,String> map=null;
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(ZpzOauthCommonConstant.SIGN_KEY.getBytes())
                    .parseClaimsJws(auth).getBody();
            Object ucode = claims.get("ucode", Object.class);
            Object client_id = claims.get("client_id", Object.class);
            map=new HashMap<>();
            map.put("ucode",ucode!=null?ucode.toString():null);
            map.put("client_id",client_id!=null?client_id.toString():null);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return map;
    }
    /*
     * springboot 不允许将值注入给静态变量，可以借用spring的set方法给静态变量赋值
     * */
    /*
     * 获取用户当前登录用户所有的用户信息
     * */
    public static Map<String,String> getUserInfo(HttpServletRequest request){
        Map<String,String> map=null;
        try {
            String auth = request.getHeader("Authorization");
            auth = auth.substring(7, auth.length());
            Claims claims = Jwts.parser()
                    .setSigningKey(ZpzOauthCommonConstant.SIGN_KEY.getBytes())
                    .parseClaimsJws(auth).getBody();
            Object ucode = claims.get("ucode", Object.class);
            Object grantType = claims.get("grant_type", Object.class);
            map=new HashMap<>();
            map.put("jwt_token",auth);
            map.put("grantType",grantType!=null?grantType.toString():null);
            map.put("ucode",ucode!=null?ucode.toString():null);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return map;
    }


}
